/**
* Copyright (c) By zengqh.
*
* This program is just for fun or demo, in the hope that it  
* will be useful, you can redistribute it and/or modify freely.
*
* Time: 2012/07/25
* File: OGLFrameBuffer.cpp
* Blog: http://www.cnblogs.com/zengqh/
**/

#include "OGLFrameBuffer.h"

OGLFrameBuffer::OGLFrameBuffer()
: _rs_target(NULL)
, _clr_target(NULL)
, _fbo(0)
{
	setup();
}

OGLFrameBuffer::~OGLFrameBuffer()
{
	safe_delete(_rs_target);

	for(ClrRenderTargetList::iterator iter = _clr_target.begin();
		iter != _clr_target.end(); ++iter)
	{
		RenderView* crt = (*iter);
		safe_delete(crt);
	}

	safe_delete(_rs_target);

	if (_fbo != 0)
	{
		glDeleteFramebuffers(1, &_fbo);
	}
}

void OGLFrameBuffer::Attach(u32 att, RenderView* rv)
{
	switch(att)
	{
	case ATT_DepthStencil:
		{
			if (_rs_target)
			{
				Detach(att);
			}

			_rs_target = rv;

			break;
		}

	default:
		{
			u32 id = att - ATT_Color0;
			if (id < _clr_target.size() && _clr_target[id])
			{
				Detach(att);

				_clr_target[id] = rv;
			}
		}
	}

	rv->onAttached(this, att);
}

void OGLFrameBuffer::Detach(u32 att)
{
	switch(att)
	{
	case ATT_DepthStencil:
		{
			if (_rs_target)
			{
				_rs_target->onDetached(this, att);
			}

			_rs_target = NULL;

			break;
		}
	default:
		{
			u32 id = att - ATT_Color0;
			if (id < _clr_target.size() && _clr_target[id])
			{
				RenderView* rv = _clr_target[id];

				rv->onDetached(this, att);

				_clr_target[id] = NULL;
			}
		}
	}
}

GLuint OGLFrameBuffer::getFBO() const
{
	return _fbo;
}

void OGLFrameBuffer::setup()
{
	glGenFramebuffers(1, &_fbo);
}